package com.sdkj.controller.car;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sdkj.controller.base.BaseController;
import com.sdkj.entity.Activiti;
import com.sdkj.entity.Page;
import com.sdkj.service.activiti.ActTaskService;
import com.sdkj.service.car.CarApplyService;
import com.sdkj.service.car.CarInfoService;
import com.sdkj.util.AppUtil;
import com.sdkj.util.DateUtil;
import com.sdkj.util.ObjectExcelView;
import com.sdkj.util.Const;
import com.sdkj.util.PageData;
import com.sdkj.util.Jurisdiction;

/** 
 * 类名称：CarApplyController
 * 创建人：weiHuangshuai 
 * 创建时间：2017-05-13
 */
@Controller
@RequestMapping(value="/carapply")
public class CarApplyController extends BaseController {
	
	String menuUrl = "carapply/list.do"; //菜单地址(权限用)
	@Resource(name="carapplyService")
	private CarApplyService carapplyService;
	
	@Resource 
	private CarInfoService carInfoService;
	
	@Resource
	private ActTaskService actTaskService;
	
	/**
	 * 新增
	 */
	@RequestMapping(value="/save")
	public ModelAndView save() throws Exception{
		logBefore(logger, "新增CarApply");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try {
			pd = this.getPageData();
			pd.put("apply_id", this.get32UUID());	//主键
			//为申请时间添加系统时间
			Date date = new Date();
			SimpleDateFormat dataFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
			pd.put("apply_time", dataFormat.format(date));
			pd.put("user_id", getCurrentUser().getUSER_ID()); //获取当前用户id
			pd.put("apply_person", getCurrentUser().getUSERNAME()); //获取当前用户
			carapplyService.applyAdd(pd);
			mv.addObject("msg","success");
			mv.setViewName("save_result");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		
		return mv;
	}
	
	/**
	 * 删除
	 */
	@RequestMapping(value="/delete")
	public void delete(PrintWriter out){
		logBefore(logger, "删除CarApply");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")){return;} //校验权限
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			carapplyService.delete(pd);
			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}
	
	/**
	 * 修改
	 */
	@RequestMapping(value="/edit")
	public ModelAndView edit() throws Exception{
		logBefore(logger, "修改CarApply");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try {
			pd = this.getPageData();
			carapplyService.adminEdit(pd);
			mv.addObject("msg","success");
			mv.setViewName("save_result");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		
		return mv;
	}
	
	/**
	 * 审核
	 */
	@RequestMapping(value="saveApply")
	public void saveApply(HttpServletResponse response) throws Exception{
		logBefore(logger, "审核CarApply");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")){return;} //校验权限
		PageData pd = new PageData();
		try {
			pd = this.getPageData();
			String comment = "";
			if("yes".equals(pd.getString("flag"))||"yes" == pd.getString("flag")){
				comment = "[同意] " + pd.getString("comment");
				pd.put("apply_status", 4);
				String taskDefKey = pd.getString("task_def_key");
				if("apply_end".equals(taskDefKey)){
					pd.put("apply_status", 1);
				}
			}else{
				comment = "[驳回] " + pd.getString("comment");
				pd.put("apply_status", 5);
			}
			String taskId = pd.getString("task_id");
			String procInsId = pd.getString("procIns_id");
			//为申请时间添加系统时间
			Map<String, Object> vars = new HashMap<String, Object>();
			vars.put("pass", "yes".equals(pd.getString("flag"))? "1" : "0");
			vars.put("user", pd.getString("user_id"));
			actTaskService.complete(taskId, procInsId, comment, vars);
			carapplyService.adminEdit(pd);
			JSONObject json = new JSONObject();
			json.put("msg","success");
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			out.write(json.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
	}

	
	/**
	 * 列表
	 */
	@RequestMapping(value="/list")
	public ModelAndView list(Page page){
		logBefore(logger, "列表CarApply");
		//if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			page.setPd(pd);
			List<PageData>	varList = carapplyService.list(page);	//列出CarApply列表
			mv.setViewName("car/carapply/carapply_list");
			mv.addObject("varList", varList);
			mv.addObject("pd", pd);
			mv.addObject(Const.SESSION_QX,this.getHC());	//按钮权限
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 去新增页面
	 * @throws Exception 
	 */
	@RequestMapping(value="/goAdd")
	public ModelAndView goAdd() throws Exception{
		logBefore(logger, "去新增CarApply页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		//查询所有车牌号
		List<PageData> varList = carInfoService.findNumStatus(pd);
		try {
			mv.setViewName("car/carapply/carapply_add");
			mv.addObject("msg", "save");
			mv.addObject("varList",varList);
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 根据ID找出对应信息
	 */
	@RequestMapping(value="/goDetails")
	public ModelAndView goDetails(){
		logBefore(logger, "进入详情页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			pd = carapplyService.findByIdAll(pd);
			//流程实例ID
			pd.put("procInsId", pd.getString("process_instance_id"));
			pd.put("user_id", getCurrentUser().getUSER_ID());
			List<Activiti> varList = actTaskService.histoicFlowList(pd);
			mv.setViewName("car/carapply/carapply_details");
			mv.addObject("msg", "details");
			mv.addObject("varList", varList);
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}					
		return mv;
	}
	
	/**
	 * 去修改页面
	 * @throws Exception 
	 */
	@RequestMapping(value="/goEdit")
	public ModelAndView goEdit() throws Exception{
		logBefore(logger, "去修改CarApply页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		//查询所有车牌号
		List<PageData> varList = carInfoService.findNumStatus(pd);
		try {
			pd = carapplyService.findById(pd);	//根据ID读取
			mv.setViewName("car/carapply/carapply_edit");
			mv.addObject("msg", "edit");
			mv.addObject("varList",varList);
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 批量删除
	 */
	@RequestMapping(value="/deleteAll")
	@ResponseBody
	public Object deleteAll() {
		logBefore(logger, "批量删除CarApply");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "dell")){return null;} //校验权限
		PageData pd = new PageData();		
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String DATA_IDS = pd.getString("DATA_IDS");
			if(null != DATA_IDS && !"".equals(DATA_IDS)){
				String ArrayDATA_IDS[] = DATA_IDS.split(",");
				carapplyService.deleteAll(ArrayDATA_IDS);
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	
	/*
	 * 导出到excel
	 * @return
	 */
	@RequestMapping(value="/excel")
	public ModelAndView exportExcel(){
		logBefore(logger, "导出CarApply到excel");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;}
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			Map<String,Object> dataMap = new HashMap<String,Object>();
			List<String> titles = new ArrayList<String>();
			titles.add("");	//1
			titles.add("");	//2
			titles.add("");	//3
			titles.add("");	//4
			titles.add("");	//5
			titles.add("");	//6
			titles.add("");	//7
			titles.add("");	//8
			titles.add("");	//9
			titles.add("");	//10
			titles.add("");	//11
			titles.add("");	//12
			dataMap.put("titles", titles);
			List<PageData> varOList = carapplyService.listAll(pd);
			List<PageData> varList = new ArrayList<PageData>();
			for(int i=0;i<varOList.size();i++){
				PageData vpd = new PageData();
				vpd.put("var1", varOList.get(i).getString("apply_id"));	//1
				vpd.put("var2", varOList.get(i).getString("apply_event"));	//2
				vpd.put("var3", varOList.get(i).getString("apply_time"));	//3
				vpd.put("var4", varOList.get(i).getString("apply_start_time"));	//6
				vpd.put("var5", varOList.get(i).getString("apply_end_time"));	//7
				vpd.put("var6", varOList.get(i).getString("apply_person"));	//10
				vpd.put("var7", varOList.get(i).getString("apply_remark"));	//11
				vpd.put("var8", varOList.get(i).getString("car_driver"));	//12
				vpd.put("var9", varOList.get(i).getString("driver_phone"));	//13
				vpd.put("var10", varOList.get(i).getString("driver_age"));	//14
				vpd.put("var11", varOList.get(i).getString("driver_licence"));	//15
				vpd.put("var12", varOList.get(i).getString("apply_status"));	//17
				varList.add(vpd);
			}
			dataMap.put("varList", varList);
			ObjectExcelView erv = new ObjectExcelView();
			mv = new ModelAndView(erv,dataMap);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/* ===============================权限================================== */
	public Map<String, String> getHC(){
		Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
	}
	/* ===============================权限================================== */
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}
}
